﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Text;

namespace ZDT.App
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        private static ApplicationContext context;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            OPFormTime.SetTime();
            OPFormTime.Times.Start();
            //窗体load事件加载窗体消息：
            Application.AddMessageFilter(new MyMessager());
            try
            {
                //设置应用程序处理异常方式：ThreadException处理
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                AboutForm aboutFrm = new AboutForm();
                aboutFrm.Show();
                context = new ApplicationContext();
                context.Tag = aboutFrm;
                Application.Idle += new EventHandler(Application_Idle);
                Application.Run(context);
            }
            catch (Exception  ex)
            {
                string str = GetExceptionMsg(ex, string.Empty);
                MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        static void Application_Idle(object sender, EventArgs e)
        {
             Application.Idle -= new EventHandler(Application_Idle);
             if (context.MainForm == null)
             {
                 MainForm mf = new MainForm();
                 context.MainForm = mf;
                 AboutForm af = (AboutForm)context.Tag;

                 af.msgLbl.Text = "正在初始化……";
                 Application.DoEvents();
                 mf.Init();

                 af.msgLbl.Text = "正在启动监听……";
                 Application.DoEvents();
                 mf.StartListen();

                 context.Tag = null;

                 af.Close();
                 af.Dispose();
                 mf.Show();
             }
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.Exception, e.ToString());
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //LogManager.WriteLog(str);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //LogManager.WriteLog(str);
        }

        /// <summary>
        /// 生成自定义异常消息
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="backStr">备用异常消息：当ex为null时有效</param>
        /// <returns>异常字符串文本</returns>
        static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】：" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】：" + ex.GetType().Name);
                sb.AppendLine("【异常信息】：" + ex.Message);
                sb.AppendLine("【堆栈调用】：" + ex.StackTrace);
            }
            else
            {
                sb.AppendLine("【未处理异常】：" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }

    }

    internal class MyMessager : IMessageFilter
    {
        public static int TimeNumber = 0;
        //截取鼠标、键盘消息，进行处理
        public bool PreFilterMessage(ref System.Windows.Forms.Message m)
        {
            //513,左键；516，右键；519，滚轮点击；520滚轮点击轮动；256，回车；257，其他键盘键。522，滚轮滚动
            if (m.Msg != 513 && m.Msg != 516 && m.Msg != 519 && m.Msg != 520 && m.Msg != 522 && m.Msg != 256 && m.Msg != 257)
            {
            }
            else
            {
                TimeNumber = 0;
            }
            return false;
        }
    }
    /// <summary>
    /// 定义监控类
    /// </summary>
    internal class OPFormTime
    {
        private static Timer time = new Timer();

        public static Timer Times
        {
            get { return time; }
        }
        public static int IDLESecond = 5;

        public static void SetTime()
        {
            time.Interval = 1000;
            time.Tick += new EventHandler(time_Tick);
        }

        private static void time_Tick(object sender, EventArgs e)
        {
            MyMessager.TimeNumber++;
            int num = MyMessager.TimeNumber;
            if (num == IDLESecond * 60)
            {
                num = 0;
                Application.Restart();
            }
        }
    }

}
